package HOT;

/**
 * Author  zxy
 * Date  2023/6/8 下午 5:01
 */

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}


public class RemoveNthFromEnd {

    public ListNode removeNthFromEnd(ListNode head, int n) {

        // HOT.ListNode ret = head;
        // HOT.ListNode temp = head;

        // int count = 0;
        // while (temp != null) {
        //     count++;
        //     temp = temp.next;
        // }

        // temp = head;

        // if (count == 1 || count == n) {
        //     return head.next;
        // }

        // count -= n;
        // while (count > 1) {
        //     count--;
        //     temp = temp.next;
        // }

        // temp.next = temp.next.next;

        // return ret;


        // 哑结点
        ListNode dummy = new ListNode(0, head);

        ListNode fast = head;
        ListNode slow = dummy;

        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }

        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }

        slow.next = slow.next.next;

        return dummy.next;
    }
}